<template>
  <div class="course-manage-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="manage-card">
          <template #header>
            <div class="card-header">
              <h3>课程管理</h3>
              <el-button type="primary" @click="showAddCourseDialog">
                <el-icon><Plus /></el-icon>添加课程
              </el-button>
            </div>
          </template>
          
          <el-table 
            :data="courseStore.courses"
            style="width: 100%"
            :header-cell-style="{ background: '#f5f7fa' }"
          >
            <el-table-column prop="code" label="课程代码" width="100" />
            <el-table-column prop="name" label="课程名称" width="180" />
            <el-table-column prop="teacher" label="教师" width="120" />
            <el-table-column prop="credits" label="学分" width="80" />
            <el-table-column prop="type" label="类型" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.type === '必修课' ? 'danger' : 'success'">
                  {{ scope.row.type }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="容量" width="120">
              <template #default="scope">
                <div>
                  {{ scope.row.enrolled }}/{{ scope.row.capacity }}
                  <el-progress 
                    :percentage="(scope.row.enrolled / scope.row.capacity) * 100"
                    :status="getCapacityStatus(scope.row)"
                    :stroke-width="5"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="上课时间" width="200">
              <template #default="scope">
                <el-popover
                  placement="top"
                  :width="300"
                  trigger="hover"
                >
                  <template #default>
                    <div v-for="(s, index) in scope.row.schedule" :key="index" class="schedule-item">
                      {{ getDayText(s.day) }} {{ s.startTime }}-{{ s.endTime }} ({{ s.location }})
                    </div>
                  </template>
                  <template #reference>
                    <div class="schedule-preview">
                      <el-tag v-for="(s, index) in scope.row.schedule.slice(0, 1)" :key="index" size="small">
                        {{ getDayText(s.day) }} {{ s.startTime }}
                      </el-tag>
                      <el-tag v-if="scope.row.schedule.length > 1" size="small" type="info">
                        +{{ scope.row.schedule.length - 1 }}
                      </el-tag>
                    </div>
                  </template>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button-group>
                  <el-button type="primary" size="small" @click="editCourse(scope.row)">
                    <el-icon><Edit /></el-icon>编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="deleteCourse(scope.row)">
                    <el-icon><Delete /></el-icon>删除
                  </el-button>
                  <el-button type="info" size="small" @click="viewStudents(scope.row)">
                    <el-icon><User /></el-icon>查看学生
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 添加/编辑课程对话框 -->
    <el-dialog
      v-model="courseFormVisible"
      :title="isEditing ? '编辑课程' : '添加课程'"
      width="600px"
    >
      <el-form ref="courseFormRef" :model="courseForm" :rules="courseRules" label-width="100px">
        <el-form-item label="课程代码" prop="code">
          <el-input v-model="courseForm.code" placeholder="例如：CS101" />
        </el-form-item>
        
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="courseForm.name" placeholder="例如：计算机导论" />
        </el-form-item>
        
        <el-form-item label="教师" prop="teacher">
          <el-input v-model="courseForm.teacher" placeholder="例如：张教授" />
        </el-form-item>
        
        <el-form-item label="学分" prop="credits">
          <el-input-number v-model="courseForm.credits" :min="1" :max="10" />
        </el-form-item>
        
        <el-form-item label="课程类型" prop="type">
          <el-select v-model="courseForm.type" placeholder="请选择课程类型">
            <el-option label="必修课" value="必修课" />
            <el-option label="选修课" value="选修课" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="课程容量" prop="capacity">
          <el-input-number v-model="courseForm.capacity" :min="1" :max="200" />
        </el-form-item>
        
        <el-form-item label="已选人数" prop="enrolled">
          <el-input-number v-model="courseForm.enrolled" :min="0" :max="courseForm.capacity" />
        </el-form-item>
        
        <el-form-item label="课程描述" prop="description">
          <el-input
            v-model="courseForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入课程描述"
          />
        </el-form-item>
        
        <el-divider>上课时间安排</el-divider>
        
        <div v-for="(schedule, index) in courseForm.schedule" :key="index" class="schedule-form-item">
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item :label="index === 0 ? '星期' : ''" :prop="`schedule.${index}.day`" :rules="{ required: true, message: '请选择星期', trigger: 'change' }">
                <el-select v-model="schedule.day" placeholder="请选择星期">
                  <el-option v-for="day in weekDays" :key="day.value" :label="day.label" :value="day.value" />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :span="6">
              <el-form-item :label="index === 0 ? '开始时间' : ''" :prop="`schedule.${index}.startTime`" :rules="{ required: true, message: '请选择开始时间', trigger: 'change' }">
                <el-time-select
                  v-model="schedule.startTime"
                  placeholder="开始时间"
                  start="08:00"
                  step="00:30"
                  end="21:00"
                />
              </el-form-item>
            </el-col>
            
            <el-col :span="6">
              <el-form-item :label="index === 0 ? '结束时间' : ''" :prop="`schedule.${index}.endTime`" :rules="{ required: true, message: '请选择结束时间', trigger: 'change' }">
                <el-time-select
                  v-model="schedule.endTime"
                  placeholder="结束时间"
                  start="08:00"
                  step="00:30"
                  end="21:30"
                  :min-time="schedule.startTime"
                />
              </el-form-item>
            </el-col>
            
            <el-col :span="6">
              <el-form-item :label="index === 0 ? '教室' : ''" :prop="`schedule.${index}.location`" :rules="{ required: true, message: '请输入教室', trigger: 'blur' }">
                <el-input v-model="schedule.location" placeholder="例如：A-101" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-button v-if="courseForm.schedule.length > 1" type="danger" circle size="small" class="remove-schedule-btn" @click="removeSchedule(index)">
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
        
        <div class="add-schedule">
          <el-button type="primary" @click="addSchedule">
            <el-icon><Plus /></el-icon>添加上课时间
          </el-button>
        </div>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="courseFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCourseForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 查看学生对话框 -->
    <el-dialog
      v-model="studentsDialogVisible"
      title="已选学生列表"
      width="500px"
    >
      <div v-if="selectedCourse">
        <h3>{{ selectedCourse.name }} ({{ selectedCourse.code }})</h3>
        <p>已选人数：{{ selectedCourse.enrolled }}/{{ selectedCourse.capacity }}</p>
        
        <el-table :data="mockStudents" style="width: 100%" border>
          <el-table-column prop="id" label="学号" width="100" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="department" label="院系" />
          <el-table-column prop="grade" label="年级" width="80" />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useCourseStore } from '../../stores/course'
import { ElMessage, ElMessageBox } from 'element-plus'

const courseStore = useCourseStore()

// 表单相关
const courseFormRef = ref(null)
const courseFormVisible = ref(false)
const isEditing = ref(false)
const editingCourseId = ref(null)

// 查看学生相关
const studentsDialogVisible = ref(false)
const selectedCourse = ref(null)

// 星期几
const weekDays = [
  { label: '周一', value: 1 },
  { label: '周二', value: 2 },
  { label: '周三', value: 3 },
  { label: '周四', value: 4 },
  { label: '周五', value: 5 },
  { label: '周六', value: 6 },
  { label: '周日', value: 7 }
]

// 课程表单数据
const courseForm = reactive({
  code: '',
  name: '',
  teacher: '',
  credits: 3,
  type: '必修课',
  capacity: 50,
  enrolled: 0,
  description: '',
  schedule: [
    { day: 1, startTime: '08:00', endTime: '09:40', location: '' }
  ]
})

// 表单验证规则
const courseRules = {
  code: [
    { required: true, message: '请输入课程代码', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在2到10个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入课程名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  teacher: [
    { required: true, message: '请输入教师姓名', trigger: 'blur' }
  ],
  credits: [
    { required: true, message: '请输入学分', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择课程类型', trigger: 'change' }
  ],
  capacity: [
    { required: true, message: '请输入课程容量', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入课程描述', trigger: 'blur' }
  ]
}

// 模拟学生数据
const mockStudents = [
  { id: '2023001', name: '张三', department: '计算机科学与技术', grade: '大二' },
  { id: '2023002', name: '李四', department: '软件工程', grade: '大二' },
  { id: '2023003', name: '王五', department: '计算机科学与技术', grade: '大三' },
  { id: '2023004', name: '赵六', department: '人工智能', grade: '大一' },
  { id: '2023005', name: '钱七', department: '网络空间安全', grade: '大四' }
]

// 获取容量状态
const getCapacityStatus = (course) => {
  const percent = (course.enrolled / course.capacity) * 100
  if (percent >= 100) return 'exception'
  if (percent >= 80) return 'warning'
  return 'success'
}

// 获取星期文本
const getDayText = (day) => {
  const dayObj = weekDays.find(d => d.value === day)
  return dayObj ? dayObj.label : ''
}

// 添加上课时间
const addSchedule = () => {
  courseForm.schedule.push({ day: 1, startTime: '08:00', endTime: '09:40', location: '' })
}

// 移除上课时间
const removeSchedule = (index) => {
  courseForm.schedule.splice(index, 1)
}

// 显示添加课程对话框
const showAddCourseDialog = () => {
  isEditing.value = false
  editingCourseId.value = null
  resetCourseForm()
  courseFormVisible.value = true
}

// 编辑课程
const editCourse = (course) => {
  isEditing.value = true
  editingCourseId.value = course.id
  
  // 复制课程数据到表单
  Object.keys(courseForm).forEach(key => {
    if (key === 'schedule') {
      courseForm.schedule = JSON.parse(JSON.stringify(course.schedule))
    } else {
      courseForm[key] = course[key]
    }
  })
  
  courseFormVisible.value = true
}

// 删除课程
const deleteCourse = (course) => {
  ElMessageBox.confirm(
    `确定要删除课程 "${course.name}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    courseStore.deleteCourse(course.id)
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 查看已选学生
const viewStudents = (course) => {
  selectedCourse.value = course
  studentsDialogVisible.value = true
}

// 重置课程表单
const resetCourseForm = () => {
  courseForm.code = ''
  courseForm.name = ''
  courseForm.teacher = ''
  courseForm.credits = 3
  courseForm.type = '必修课'
  courseForm.capacity = 50
  courseForm.enrolled = 0
  courseForm.description = ''
  courseForm.schedule = [{ day: 1, startTime: '08:00', endTime: '09:40', location: '' }]
  
  if (courseFormRef.value) {
    courseFormRef.value.resetFields()
  }
}

// 提交课程表单
const submitCourseForm = async () => {
  if (!courseFormRef.value) return
  
  await courseFormRef.value.validate(async (valid) => {
    if (valid) {
      const courseData = {
        id: isEditing.value ? editingCourseId.value : undefined,
        code: courseForm.code,
        name: courseForm.name,
        teacher: courseForm.teacher,
        credits: courseForm.credits,
        type: courseForm.type,
        capacity: courseForm.capacity,
        enrolled: courseForm.enrolled,
        description: courseForm.description,
        schedule: courseForm.schedule
      }
      
      if (isEditing.value) {
        courseStore.updateCourse(courseData)
        ElMessage.success('课程更新成功')
      } else {
        courseStore.addCourse(courseData)
        ElMessage.success('课程添加成功')
      }
      
      courseFormVisible.value = false
      resetCourseForm()
    } else {
      ElMessage.warning('请正确填写表单')
    }
  })
}
</script>

<style scoped>
.course-manage-container {
  padding: 0 10px;
}

.manage-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
}

.schedule-form-item {
  position: relative;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #ebeef5;
}

.remove-schedule-btn {
  position: absolute;
  right: 0;
  top: 10px;
}

.add-schedule {
  margin-top: 20px;
  text-align: center;
}

.schedule-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.schedule-item {
  margin-bottom: 8px;
}
</style> 